package org.egedede.processmanager;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import org.egedede.processmanager.events.ProcessListener;
import org.egedede.processmanager.logs.ProcessLog;
import org.egedede.processmanager.logs.ProcessLogListener;

public class ProcessDefinition {
	private final String label;
	private final String commandLine;
	private final String workingDir;
	private final Map<String, String> env;
	private final SingleProcess process;

	public ProcessDefinition(String label, String commandLine, String workingDir, Map<String, String> env) {
		this.label = label;
		this.commandLine = commandLine;
		this.workingDir = workingDir;
		this.env = env;
		this.process = new SingleProcess(UUID.randomUUID().toString(), label, commandLine, workingDir, env);
	}

	public String getLabel() {
		return this.label;
	}

	public String getCommand() {
		return this.commandLine;
	}

	public String getWorkingDir() {
		return this.workingDir;
	}

	public Map<String, String> getEnv() {
		return this.env;
	}

	public void addLogListener(ProcessLogListener l) {
		this.process.getLog().addListener(l);
	}

	public boolean isFinished() {
		return this.process != null && this.process.isFinished();
	}

	public int exitValue() {
		return this.process.exitValue();
	}

	public ProcessLog getLog() {
		return this.process.getLog();
	}

	public SingleProcess getProcess() {
		return this.process;
	}

	public void start() {
		this.process.start();
	}

	public void addProcessListener(ProcessListener listener) {
		this.process.addListener(listener);
	}

	public void startAndWait() {
		this.process.start(true);
	}

	@Override
	protected Object clone() throws CloneNotSupportedException {
		ProcessDefinition result = new ProcessDefinition(this.label, this.commandLine, this.workingDir,
				new HashMap<String, String>(this.env));
		return result;
	}

}
